import time, os
from django.db import models

from django.conf import settings
from django.utils import timezone

from utils.exceptions import CustomError
from utils.tencen import TenCenCos


class UploadManager(models.Manager):
    def upload(self, file, path, user):
        # 文件名
        file_name = "%s.%s" % (
            timezone.now().strftime('%Y%m%d%H%M%S%f'),
            file.name.split('.')[-1]
        )
        file_name = file_name.lower()

        # 保存文件到本地
        local_file_path = self.save_file_to_local(file, file_name)

        # 图片保存到腾讯云
        tencen_cos = TenCenCos()
        save_path = '%s/%s' % (path, file_name)
        tencen_cos.upload(local_file_path, save_path)

        instance = self.model(file_path=save_path, user=user)
        instance.save()

        return instance

    def save_file_to_local(self, file, file_name):
        folder_path = settings.TEMP_ROOT
        # 判断图片文件夹是否存在
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        # 删除历史图片
        now = int(time.time())
        old_files = os.listdir(folder_path)
        for old_file in old_files:
            old_file_path = os.path.join(folder_path, old_file)
            try:
                if os.path.isfile(old_file_path):
                    last = int(os.stat(old_file_path).st_atime)
                    if now - last > 180:
                        os.remove(old_file_path)
            except:
                pass
        # 保存到本地
        local_file_path = "%s/%s" % (settings.TEMP_ROOT, file_name)
        with open(local_file_path, 'wb+') as fb:
            for chunk in file.chunks():
                fb.write(chunk)
        return local_file_path


vote_image = 'vote_image'
bargain_image = 'bargain_image'


class Upload(models.Model):
    file_path = models.CharField(verbose_name='文件路径', max_length=250)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'操作人', on_delete=models.PROTECT)
    notes = models.CharField(verbose_name='备注', max_length=250, null=True)

    objects = UploadManager()

    def get_url(self):
        return '%s%s' % (settings.TENCENT_CLOUD['IMAGE_URL'], self.file_path)

    class Meta:
        db_table = 'system_upload'
        verbose_name = '上传文件'
        ordering = ['-create_time']
        default_permissions = ()

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的Uploadid')

        instance = Upload.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的Upload实例')
        return instance


class Option(models.Model):
    ACTIVITY_THEME = 1
    BG_COLOR = 2

    TYPE_CHOICES = (
        (ACTIVITY_THEME, '活动主题'),
        (BG_COLOR, '背景色')
    )
    TYPE_JSON = [{'code': item[0], 'codeName': item[1]} for item in TYPE_CHOICES]
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name='类别')
    name = models.CharField(verbose_name='名称', max_length=100)
    sort = models.PositiveSmallIntegerField(verbose_name='排序', help_text='越小越靠前', default=0, blank=True)
    notes = models.CharField(max_length=500, verbose_name='备注', null=True, blank=True)

    class Meta:
        db_table = 'system_option'
        verbose_name = '系统分类'
        ordering = ['sort']


class Area(models.Model):
    PROVINCE = 0
    CITY = 1
    COUNTY = 2
    LEVEL_CHOICES = (
        (PROVINCE, u'省级'),
        (CITY, u'市级'),
    )
    level = models.IntegerField(u'层级', choices=LEVEL_CHOICES)
    name = models.CharField(max_length=15, verbose_name='省份')
    code = models.CharField(max_length=10, verbose_name='编码')
    lat = models.FloatField(verbose_name='纬度')
    lng = models.FloatField(verbose_name='经度')
    province = models.ForeignKey('Area', verbose_name='所属省', related_name='province_children', on_delete=models.PROTECT,
                                 blank=True, null=True)

    class Meta:
        verbose_name = u"地区"
        db_table = "system_area"
